package com.myapp.api.tools;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

import java.util.Date;

public class JWTUtils {
    public static final String TOKEN_HEADER = "Authorization";
    public static final String TOKEN_PREFIX = "Bearer ";
    private static final String SECRET = "P@ssw02d";
    private static final String ISS = "vxhly.github.io";

    // 过期时间是 3600 秒，既是 1 个小时
    private static final long EXPIRATION = 3600 * 24;

    // 选择了记住我之后的过期时间为 7 天
    private static final long EXPIRATION_REMEMBER = 3600 * 24 * 7;

    // 创建token
    public static String createToken(String account, String username, String role, boolean isRememberMe) {
        long expiration = isRememberMe ? EXPIRATION_REMEMBER : EXPIRATION;
        return TOKEN_PREFIX + Jwts.builder()
                .signWith(SignatureAlgorithm.HS512, SECRET)
                .setIssuer(ISS)
                .claim("account", account)
                .claim("username", username)
                .claim("role", role)
                .setIssuedAt(new Date())
                .setExpiration(new Date(System.currentTimeMillis() + expiration * 1000))
                .compact();
    }

    // 是否已过期
    public static boolean isExpiration(String token){
        return parseJWT(token).getExpiration().before(new Date());
    }

    public static Claims parseJWT(String token){
        try {
            return Jwts.parser()
                    .setSigningKey(SECRET)
                    .parseClaimsJws(token.replace(TOKEN_PREFIX,""))
                    .getBody();
        } catch(Exception ex) {
            throw new IllegalStateException(ex.getMessage());
        }
    }
}
